<template>
  <div id="container"></div>
</template>
<script>
import { initLine } from "@/util/carTrajectory";
import { updateCarTrajectory } from '@/api/index'
import AMapLoader from "@amap/amap-jsapi-loader";
import { getOrderList } from '../../../api';
window._AMapSecurityConfig = {
  securityJsCode: "237716e4a44b4c1b1e45e9280e7f189f"
};
let getLongitude = 0;
let getLatitude = 0;
export default {
  name: "vehicleOrderMap",
  data() {
    return {
      map: null,
      trajectory: [],
      trajectoryList: [],
      orderId: 0
    };
  },
  // props: {
  //   trajectory: {
  //     type: Array,
  //     default: () => []
  //   },
  //   orderId: {
  //     type: Number,
  //     default: 0
  //   }
  // },
  watch: {
    trajectory(newVal) {
      this.trajectoryList = newVal; // 变化一次就更新一次
    }
  },
  mounted() {
    this.initOrderMap();
    this.getPosition();
    getOrderList(this.$cookie.get('userId'), 0).then(({data}) => {
      console.log('轨迹', data.data[0].trajectory);
      console.log('订单id', data.data[0].id);
      this.trajectory = data.data[0].trajectory;
      this.orderId = data.data[0].id;
    })
  },
  methods: {
    Rad(d) {
      // 经纬度转换成三角函数中度分表形式。
      return (d * Math.PI) / 180.0;
    },
    // lat 纬度
    // lng 经度
    // 将经纬度换成米
    GetDistance(lat1, lng1, lat2, lng2) {
      var radLat1 = this.Rad(lat1);
      var radLat2 = this.Rad(lat2);
      var a = radLat1 - radLat2;
      var b = this.Rad(lng1) - this.Rad(lng2);
      var s =
        2 *
        Math.asin(
          Math.sqrt(
            Math.pow(Math.sin(a / 2), 2) +
              Math.cos(radLat1) *
                Math.cos(radLat2) *
                Math.pow(Math.sin(b / 2), 2)
          )
        );
      s = s * 6378.137; // 地球半径;
      s = Math.round(s * 10000) / 10; // 输出为米
      return s;
    },
    /** 获取经纬度信息 */
    getPosition() {
      let that = this;
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition( // getCurrentPosition跟setInterval类似，请求多次
          (position) => {
            const setPositon = () => {
              getLongitude = position.coords.longitude; // 经度,
              getLatitude = position.coords.latitude; // 纬度
              console.log(getLongitude, getLatitude);
            };
            if (getLongitude && getLatitude) {
              const m = this.GetDistance(
                getLongitude,
                getLatitude,
                position.coords.longitude,
                position.coords.latitude
              );
              /** 位置变动1米以上才进行更新操作 */
              if (m > 1) {
                // 将经纬度加到数组里面
                this.trajectoryList.push([
                  position.coords.longitude,
                  position.coords.latitude
                ]);
                updateCarTrajectory({
                  position: this.trajectoryList.slice(-1)[0],
                  id: this.orderId
                }).then(({data}) => {
                })
                initLine(this.map, this.trajectoryList);
              }
              console.log('距离上一次变了'+m+'米');
            }
            setPositon();
            /** 5秒刷新一次位置 */
            getOrderList({
              "user_id": that.$cookie.get('userId'),
              "orderStatus": 0
            })
              .then(({data}) => {
                setTimeout(() => {
                  this.getPosition();
                }, 5000);
                // if(data.data.length === 0){
                //   console.log('当前有订单')
                // }else{
                //   console.log('当前没有订单')
                // }
              })
          },
          function (error) {
            var errorType = [
              "您拒绝共享位置信息",
              "获取不到位置信息",
              "获取位置信息超时"
            ];
            alert(errorType[error.code - 1]);
          }
        );
      }
    },
    // 初始化地图
    initOrderMap() {
      AMapLoader.load({
        key: "3ec0f4b64da67a9e6ade01ba12078cf8", // 设置您的key
        version: "2.0",
        plugins: [
          "AMap.ToolBar",
          "AMap.Driving",
          "AMap.CitySearch",
          "AMap.Geocoder",
          "AMap.PlaceSearch"
        ],
        AMapUI: {
          version: "1.1",
          plugins: []
        },
        Loca: {
          version: "2.0"
        }
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            viewMode: "3D",
            zoom: 11
          });
          /** 初始化轨迹线 */
          this.$cookie.set('map', this.map);
          initLine(this.map, this.trajectoryList);
        })
        .catch((e) => {
          console.log(e);
        });
    }
  }
};
</script>
<style lang="scss" scoped>
#container /deep/ {
  width: 100%;
  height: 100%;
  background-color: pink;
  // 去掉高德地图logo和版权信息
  .amap-logo {
    display: none;
    opacity: 0 !important;
  }
  .amap-copyright {
    opacity: 0;
  }
}
</style>